package com.itheima.web;

import cn.hutool.core.lang.UUID;
import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfoVo;
import com.itheima.service.OrderService;
import com.itheima.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @author: libin
 * @date: 2019/11/28 20:44
 * @version: 1.0
 * @describe:
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    RedisUtils redisUtils;

    @Reference
    private OrderService orderService;

    /**
     * 预约下单
     * @param orderInfoVo
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody OrderInfoVo orderInfoVo) {
        String token = orderInfoVo.getToken();
        //防止表单重复提交，验证页面随机数在redis中能否删除
        Long del = redisUtils.del(token);
        if (del == 0) {
            return new Result(false,"请不要重复提交");
        }
        //1.校验验证码是否正确
        String telephone = orderInfoVo.getTelephone();
        String validateCode = orderInfoVo.getValidateCode();
        //从redis中获取验证码
        String redisCode = redisUtils.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);

        //2判断验证码是否正确
        if (redisCode == null || !redisCode.equals(validateCode)) {
            return new Result(false,"验证码无效");
        }
        System.out.println("true");
        //3.调用这个接口就是微信预约
        orderInfoVo.setOrderType(Order.ORDERTYPE_WEIXIN);
        //4.创建订单
        return orderService.submit(orderInfoVo);
    }

    /**
     * 查找订单详情
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        Map map = orderService.findById(id);
        return new Result(true,"",map);
    }

    /**
     * 防止表单重复提交，给页面一个随机数
     * @return
     */
    @RequestMapping("/getToken")
    public Result getToken() {
        String token = UUID.randomUUID().toString();
        redisUtils.setex(token,60*5,token);
        return new Result(true,"",token);

    }

}
